package net.lovesrc.allin.controller;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import net.lovesrc.allin.Cnsts;
import net.lovesrc.allin.biz.user.UserService;
import net.lovesrc.allin.bo.User;
import net.lovesrc.allin.exception.AuthcationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/")
public class IndexController extends BaseController {

    @Autowired
    private UserService userService;

    @RequestMapping(method = RequestMethod.GET)
    public String index(HttpServletRequest request, Model model) {
        if (getCurrentUserId() != null) {
            model.addAttribute("cmpSizes", JSON.toJSONString(getCmpSizes()));
            return "index";
        } else {
            Cookie[] cookies = request.getCookies();
            if (cookies != null && cookies.length > 0) {
                for (Cookie cookie : cookies) {
                    String name = cookie.getName();
                    if ("me".equals(name)) {
                        String hashStr = cookie.getValue();
                        User user = userService.verify(hashStr);
                        if (user != null) {
                            getSession().setAttribute(Cnsts.SESSION_KEY_USER_ID, user.getId());
                            model.addAttribute("cmpSizes", JSON.toJSONString(getCmpSizes()));
                            return "index";
                        }
                    }
                }
            }
        }
        return "login/index";
    }

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String login(String username, String password, Model model, HttpServletResponse response) throws AuthcationException {

        try {
            User user = userService.verify(username, password);
            getSession().setAttribute(Cnsts.SESSION_KEY_USER_ID, user.getId());
            Cookie meCookie = new Cookie("me", user.getHashStr());
            meCookie.setMaxAge(24 * 60 * 60);
            response.addCookie(meCookie);
        } catch (Exception e) {
            model.addAttribute("msg", e.getMessage());
            return "login/index";
        }
        return "redirect:/";
    }

    public Map<String, Integer> getCmpSizes() {

        final String userId = getCurrentUserId();
        Map<String, Integer> result = Maps.newHashMap();
        List<Map<String, Object>> rows = jdbcTemplate.queryForList("select * from t_cmp_size where userId = ?", userId);
        for (Map<String, Object> row : rows) {
            result.put(row.get("cmpId").toString(), Integer.valueOf(row.get("width").toString()));
        }
        return result;
    }

    @GetMapping("/dida/route/ride/{id}")
    public Object index(@PathVariable String id, Model model) {
        model.addAttribute("url", "didapinche://order/?rid=" + id + "&role=2");
        return "dida/app-link";
    }


}
